﻿// *********************************************************************
// * Copyright © 2013 Scanvaegt Nordic A/S
// *
// * This file is the property of Scanvaegt Nordic A/S and may not be 
// * distributed without the written consent of the author.    
// ********************************************************************

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using SqlPad.Library.Interfaces;

namespace SqlPad.Library.QueryTransformers
{
    public class HtmlTransformDataTable : IQueryTransform<DataTable>
    {

        public string Transform(IQueryResult<DataTable> data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string result;
            string xml;

            var resultBuilder = new StringBuilder();

            using (var stream = new MemoryStream())
            {
                data.Result.WriteXml(stream, XmlWriteMode.IgnoreSchema);
                stream.Position = 0;
                using (var reader = new StreamReader(stream))
                {
                    xml = reader.ReadToEnd();
                }
            }

            var xslt = Properties.Resources.htmlTable;
            var transformer = new XslCompiledTransform();

            using (var xslDoc = new MemoryStream(Encoding.UTF8.GetBytes(xslt)))
            {
                using (var stringReader = new StringReader(xml))
                {
                    using (var xslReader = new XmlTextReader(xslDoc))
                    {
                        transformer.Load(xslReader);
                        using (XmlReader xmlReader = new XmlTextReader(stringReader))
                        {
                            using (var writer = new StringWriter())
                            {
                                transformer.Transform(xmlReader, null, writer);
                                var text = writer.ToString();
                                var i = text.IndexOf("?>", StringComparison.Ordinal);
                                if (i != -1)
                                {
                                    text = text.Substring(i + 2);
                                }

                                result = text;
                            }
                        }
                    }
                }
            }  


            return result;
        }
    }
}